// pages/home/home.js
import {
  HomeModel
} from '../../models/home.js';

import {
  Lock
} from '../../models/lock.js';

import {
  Log
} from '../../utils/log.js';

import {
  Token
} from '../../utils/token.js';

import {
  enums
} from '../../utils/enums.js';

import {
  Tip
} from '../../utils/tip';

const util = require('../../utils/util.js');

const homeModel = new HomeModel();

const lock = new Lock();

const log = new Log();

const tip = new Tip();

const token = new Token();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    items: [],
    tabs: [{
      "tabName": "推荐",
      "key": "1",
    }, {
      "tabName": "情侣",
      "key": "2",
    }, {
      "tabName": "男生",
      "key": "3",
    }, {
      "tabName": "女生",
      "key": "4",
    }, {
      "tabName": "卡通动漫",
      "key": "5",
    }, {
      "tabName": "风景静物",
      "key": "6",
    }, {
      "tabName": "唯美",
      "key": "7",
    }, {
      "tabName": "可爱",
      "key": "8",
    }, {
      "tabName": "文字",
      "key": "9",
    }, {
      "tabName": "欧美",
      "key": "10",
    }, {
      "tabName": "影视明星",
      "key": "11",
    }, {
      "tabName": "体育",
      "key": "12",
    }, {
      "tabName": "汽车品牌",
      "key": "13",
    }, {
      "tabName": "其他",
      "key": "14",
    }],
    loadingHidden: true,
    pageIndex: 1,
    loadMore: false,
    startTime: new Date().getTime(),
    placeholder: "输入关键字搜索",
    logData: {
      // 开始加载=1，加载成功=2，加载失败=3
      "action": 1,
      "loadingTime": 0,
      // 加载类型：1-读取缓存，2-从接口拉新数据
      "loadingWay": 2,
      // 自动加载=1，用户下拽加载=2，底部加载=3
      "type": 1,
      "errCode": ""
    },
    loading: false,
    msg: {
      show: false,
      type: 'success',
      duration: 2000,
      content: '为您成功推荐50条内容'
    },
    activeKey: {
      "tabName": "推荐",
      "key": "1",
    },
    // addTip: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    /**
     * 因为js异步调用，onLaunch与onLoad无执行顺序，所以此处再次调用token.verify()
     */
    token.verify().then(res => {
      if (res) {
        this._loadData();
      }
    });

    /**
     * 添加用户指导
     */
    tip.init();

  },

  /**
   * 私有方法,加载数据
   */
  _loadData() {
    let that = this;

    if (lock.isLocked()) {
      return;
    }

    // 加锁
    lock.lock();

    homeModel.home(this.data.activeKey.key, this.data.pageIndex).then(res => {

      // 记录日志
      that.data.logData.action = 2;
      // 自动加载=1，用户下拽加载=2，底部加载=3
      that.data.logData.type = that.data.pageIndex > 1 ? 3 : 2;
      let now = new Date().getTime();
      // 计算时间差
      let gap = util.timeGap(this.data.startTime, now);
      that.data.logData.loadingTime = gap;

      that.setData({
        items: res.data,
      });

      // 记录日志
      let ev = {
        "ett": new Date().getTime(), //客户端事件产生时间
        "en": "loading", //事件名称
        "kv": that.data.logData
      }
      log.addToEts(ev);

      // 数据加载完成关闭骨架视图
      that._closeSkeletonView();

      // 关闭底部提示
      that._closeLoadMoreTip();

      lock.unlock();
    }).catch(err => {
      that.data.logData.action = 3;
      // 自动加载=1，用户下拽加载=2，底部加载=3
      that.data.logData.type = that.data.pageIndex > 1 ? 3 : 2;
      that.data.logData.errCode = err.code;

      // 记录日志
      let ev = {
        "ett": new Date().getTime(), //客户端事件产生时间
        "en": "loading", //事件名称
        "kv": that.data.logData
      }
      log.addToEts(ev);

      // 释放锁
      lock.unlock();
    });

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

    // 解决onLoad中不能确保每次都能读取到缓存数据
    let category = wx.getStorageSync('category');

    if (category) {
      this.setData({
        tabs: category
      })
    }

    let hotWords = wx.getStorageSync(enums.hot);
    if (hotWords.length > 0) {
      let keyword = util.searchPlaceholder(hotWords);
      this.setData({
        placeholder: `大家都在搜"${keyword}"`
      })
    }

    // let addTip = wx.getStorageSync(enums.addTip);
    // if (!addTip) {
    //   // 开启提示
    //   this.setData({
    //     addTip: !addTip
    //   })

    //   // 3秒之后关闭提示
    //   setTimeout(() => {
    //     wx.setStorageSync(enums.addTip, !addTip);
    //     this.setData({
    //       addTip: addTip
    //     })
    //   }, 3000);
    // }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 切换分类
   */
  _changeData() {

    let that = this;
    homeModel.home(this.data.activeKey.key, this.data.pageIndex).then(res => {

      // 先清空
      that.setData({
        items: [],
      });

      // 重新设置
      that.selectComponent('#content').recommend(0, res.data);

      that._closeLoading();
      that._showMsg(res.data.length);
    });
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    this.data.pageIndex++;
    this._showLoadMoreTip();
    setTimeout(() => {
      this._loadData();
    }, 300);
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return {
      title: "长佩 · 美图陪伴好心情",
    }
  },
  _closeSkeletonView() {
    this.setData({
      loadingHidden: false
    });
  },
  toDetail(e) {
    let that = this;
    let params = e.detail;
    let oauth = wx.getStorageSync('oauth');

    if (!oauth) {
      // 提示授权
      wx.getUserProfile({
        lang: 'zh_CN',
        desc: '用于完善个人资料',
        success: (res) => {
          token.updateUserInfo(res.userInfo).then(oRes => {
            // 授权成功,展示个人页面数据
            if (oRes) {
              that._showLoading();
              that._stopRefresh();
            }
          });
        }
      })
    } else {
      // 记录日志
      log.logHistory(params.id);

      // 跳转到详情页
      wx.navigateTo({
        url: `../detail/detail?id=${params.id}&entry=1`,
      });
    }
  },
  onSearch() {
    wx.navigateTo({
      url: '../search/search',
    })
  },
  changeTabs(e) {
    let that = this;

    that.setData({
      activeKey: that.data.tabs[e.detail.currentIndex]
    });
    // 直接清除
    that.selectComponent('#content').clearFall();
    that._showLoading();

    setTimeout(() => {
      token.verify().then(res => {
        if (res) {
          that._changeData();
        }
      });
    }, 800);
  },
  _showLoadMoreTip() {
    this.setData({
      loadMore: true
    });
  },
  _closeLoadMoreTip() {
    this.setData({
      loadMore: false
    });
  },
  _showLoading() {
    this.setData({
      loading: true
    })
  },
  _closeLoading() {
    this.setData({
      loading: false
    })
  },
  _showMsg(total = 50) {
    let tip = total > 0 ? `为您成功推荐${total}条内容` : '暂无内容推荐～';
    let sign = total > 0 ? 'success' : 'warning';
    this.setData({
      msg: {
        show: true,
        type: sign,
        duration: 2000,
        content: tip
      }
    });
  },
})